package com.spic.business.alarm.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.Map.Entry;
public class HttpClientUtil {

    public static String postMap(String url,Map<String,String> headerMap,Map<String, String> contentMap) {
        CloseableHttpClient httpClient = null;
        // 解决httpClient发送https错误的问题
        SSLConnectionSocketFactory scsf = null;
        try
        {
            scsf = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            httpClient = HttpClients.custom().setSSLSocketFactory(scsf).build();
        } catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        } catch (KeyManagementException e)
        {
            e.printStackTrace();
        } catch (KeyStoreException e)
        {
            e.printStackTrace();
        }
        String result = null;
        HttpPost post = new HttpPost(url);
        List<NameValuePair> content = new ArrayList<NameValuePair>();
        Iterator iterator = contentMap.entrySet().iterator();           //将content生成entity
        while(iterator.hasNext()){
            Entry<String,String> elem = (Entry<String, String>) iterator.next();
            content.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
        }
        CloseableHttpResponse response = null;
        try {
            if(headerMap!=null){
                Iterator headerIterator = headerMap.entrySet().iterator();          //循环增加header
                while(headerIterator.hasNext()){
                    Entry<String,String> elem = (Entry<String, String>) headerIterator.next();
                    post.addHeader(elem.getKey(),elem.getValue());
                }
            }
            if(content.size() > 0){
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(content,"UTF-8");
                post.setEntity(entity);
            }
            response = httpClient.execute(post);            //发送请求并接收返回数据
            if(response != null && response.getStatusLine().getStatusCode() == 200)
            {
                HttpEntity entity = response.getEntity();       //获取response的body部分
                result = EntityUtils.toString(entity);          //读取reponse的body部分并转化成字符串
            }
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                if(response != null)
                {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        // POST：请求携带JSON参数
//        String postUrl = "https://10.237.35.10/api/car/queryAlarmDetail";

//        Map<String, String> contentMap = new HashMap<>();
//        contentMap.put("begintime","2022-05-31 00:00:00");
//        contentMap.put("endtime","2022-05-31 23:59:59");
//        contentMap.put("currentPage","1");
//        contentMap.put("pageRecords","2");
//        contentMap.put("armType","49,11");
//        String message = postMap(postUrl,null,contentMap);
//        System.out.println(message);

        //企业部门车辆列表查询,对接的中国移动端机动车管理系统
        String postUrl = "https://10.237.35.10/api/car/queryCorpDeptVehicleList";

        Map<String, String> contentMap = new HashMap<>();
        //contentMap.put("pageNo","1");
        contentMap.put("pageSize","1000");
        String message = postMap(postUrl,null,contentMap);
        System.out.println(message);

//        {"armType":"11",
//                "currentPage":"1",
//                "pageRecords":"10",
//                "begintime":"2022-11-02",
//                "endtime":"2022-11-04"
//        }
//        JSONObject param = new JSONObject();
//        param.put("currentPage", "1");
//        param.put("pageRecords", "10");
//        param.put("begintime", "2022-11-02");
//        param.put("endtime", "2022-11-04");
//        JSONObject body = new JSONObject();
//        body.put("armType", "11");
//
//        JSONObject reqParams = new JSONObject();
//        reqParams.put("param", param);
//        reqParams.put("body", body);
//        System.out.println(JSONObject.toJSONString(reqParams));


//        String postUrl = "https://cloud.yuejin360.com/index.php/home/webapi";
//        // 入参实体
//        // 实体转JSON字符串
//        String jsonString = "{\"appcode\":\"405cc23b4830f4c28684cf55ac4a2d0d\"}";
//
//        Map<String, String> contentMap = new HashMap<>();
//        contentMap.put("mode","get_gnss");
//        contentMap.put("pointname","NK-01,NK-02,NK-03,NK-04,NK-05,NK-06,NK-07,NK-08,NK-09,NK-10,NK-11,NK-12");
//        contentMap.put("starttime","2022-06-01 00:00:00");
//        contentMap.put("endtime","2022-06-06 23:59:59");
//        Map<String, String> headerMap = new HashMap<>();
//        headerMap.put("appcode",jsonString);
//        String message = postMap(postUrl,headerMap,contentMap);
//        System.out.println(message);
    }
}
